const app = getApp();
const db = wx.cloud.database().collection("venue");
const chooseLocation = requirePlugin('chooseLocation');
Page({
  data: {
    value: '',
    equipmentList: [],
    enable: false,
    actionText: '',
    loadingProps: { size: '50rpx' },
    isEditing: false,
    editId: null,
    venue: '',
    imgUrl: '',
    location: '',
    contact: '',
    rent: '',
    address: "",
    locationName: "",
    latitude: "", // 维度
    longitude: "", // 经度
  },
  onLoad: function() {
    this.getEquipmentData(); // 在页面加载时调用获取设备信息的函数
  },
 
  viewDetail(e) {
   
    const index = e.currentTarget.dataset.index; // 获取点击的<c-filmcard>的索引
    console.log(index)
    const selectedItem = this.data.equipmentList[index]; // 获取对应索引的设备信息
    
    // 检查selectedItem是否为undefined或null
    if (!selectedItem) {
      console.error("Selected item is undefined or null");
      return;
    }
    
    console.log(selectedItem._id)
    // 跳转到详细信息页面，并传递选定的设备信息
    wx.navigateTo({
      url: '/pages/film-CD-detail/film-CD-detail?id=' + selectedItem._id
    });
  },
  // 获取设备信息的函数
  getEquipmentData: function() {
    // 从 Cloud 数据库中获取 equipment 表中的数据
    db.where({
      _openid: app.globalData.user_openid,
      
    }).get().then(res => {
      console.log(res.data); // 确保获取到数据
  
      this.setData({
        equipmentList: res.data // 将获取的数据设置到页面的数据属性中
      });
    }).catch(err => {
      console.error(err);
    });
  },
  ready() {
    this.setData({ enable: true });
    setTimeout(() => {
      this.setData({ enable: false });
    }, 1000);
  },
  onRefresh() {
    this.setData({ enable: true });
    this.getEquipmentData();
    setTimeout(() => {
      this.setData({ enable: false });
    }, 1500); 
  }
  ,
  onScroll(e) {
    const { scrollTop } = e.detail;
    this.setData({ scrollTop });
  },
    
  handleDelete(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.equipmentList[index];
    const id = item._id;
    
    db.doc(id).remove()
      .then(() => {
        wx.showToast({ title: '删除成功', icon: 'none' });
        this.getEquipmentData();
      })
      .catch(err => {
        wx.showToast({ title: '删除失败', icon: 'none' });
        console.error('Failed to delete item:', err);
      });
  },

  //地图相关
  onShow() {
    const location = chooseLocation.getLocation();
    if (location) {
      this.setData({
        address: location.address || "",
        locationName: location.name || "",
        location: location.address || "",
        latitude: location.latitude || "",
        longitude: location.longitude || ""
      });
    }
  },

  showMap() {
    // 调用选择位置插件
    wx.chooseLocation({
      success: (location) => {
        const marker = {
          id: 1,
          latitude: location.latitude,
          longitude: location.longitude,
          title: '新地点',
        };
        const markers = [marker];
  
        // 更新地图标记点
        this.setData({
          markers,
          scale: 16,
          address: location.address ,
          locationName: location.name ,
          location: location.address ,
          latitude: location.latitude ,
          longitude: location.longitude 
      
        });

  
        
      },
      fail: (err) => {
        console.error('选择位置失败', err);
      }
    });
  },

  handleEdit(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.equipmentList[index];
    const location = item.location2; // 获取设备的地理位置信息
  
    // 创建地图上下文
    this.mapCtx = wx.createMapContext("myMap");
  
    // 创建标记点
    const marker = {
      id: 1,
      latitude: location[1],
      longitude: location[0],
      title: item.cname,
    };
    const markers = [marker];
  
  
    // 更新页面数据，包括已有的图片和其他信息
    this.setData({
      isEditing: true,
      editId: item._id,
      venue: item.venue,
      imgUrl: item.venue_url,
      location: item.location,
      contact: item.contact,
      rent: item.rent,
      markers,
      scale: 16,
    });
  },
  handleUpload() {
    let that = this;
    wx.chooseImage({
      success: chooseResult => {
        wx.showLoading({
          title: '上传中',
        });
        // 将图片上传至云存储空间
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: 'venue/' + (new Date()).valueOf() + '.png',
          // 指定要上传的文件的小程序临时文件路径
          filePath: chooseResult.tempFilePaths[0],
          // 成功回调
          success: res => {
            console.log('上传成功', res);
            wx.hideLoading();
            wx.showToast({
              title: '上传图片成功',
            });
            if (res.fileID) {
              // 删除旧图片
              if (that.data.oldImgUrl) {
                wx.cloud.deleteFile({
                  fileList: [that.data.oldImgUrl],
                  success: deleteRes => {
                    console.log('旧图片删除成功', deleteRes);
                  },
                  fail: err => {
                    console.error('旧图片删除失败', err);
                  }
                });
              }
              that.setData({
                zhaopian: '图片如下',
                imgUrl: res.fileID
              });
            }
          },
          fail: err => {
            wx.hideLoading();
            console.error('上传失败', err);
            wx.showToast({
              title: '上传失败，请重试',
              icon: 'none'
            });
          }
        });
      },
      fail: err => {
        console.error('选择图片失败', err);
        wx.showToast({
          title: '选择图片失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  

  publishRent() {
    const { editId, venue, imgUrl, location, contact, rent, latitude, longitude  } = this.data;
    
    if (!venue || !location || !contact || !rent) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }
    
    db.doc(editId).update({
      data: {
        venue,
        venue_url: imgUrl,
        location,
        contact,
        rent,
        location2: [longitude, latitude]
      }
    }).then(() => {
      wx.showToast({ title: '修改成功', icon: 'none' });
      this.setData({
        isEditing: false,
        editId: null,
        venue: '',
        imgUrl: '',
        location: '',
        contact: '',
        rent: ''
      });
      this.getEquipmentData();
    }).catch(err => {
      wx.showToast({ title: '修改失败，请重试', icon: 'none' });
      console.error('修改失败:', err);
    });
  },
  
  cancelEdit() {
    this.setData({
      isEditing: false,
      editId: null,
      venue: '',
      imgUrl: '',
      location: '',
      contact: '',
      rent: ''
    });
  }
});
